package com.nf.health.app.activity.ecg;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.ecgmonitorhd.ecglib.model.EcgAnalyzeResponse;
import com.ecgmonitorhd.ecglib.model.InstitBean;
import com.ecgmonitorhd.ecglib.ui.EcgActivity;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.activity.global.PictureActivity;
import com.nf.health.app.activity.global.RegisterNickActivity;
import com.nf.health.app.glide.GlideUtil;
import com.nf.health.app.http.Act;
import com.nf.health.app.http.ImageUpLoader;
import com.nf.health.app.models.EcgHistory;
import com.nf.health.app.models.UserInfo;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.Base64Util;
import com.nf.health.app.utils.DataCleanManager;
import com.nf.health.app.utils.DialogHelp;
import com.nf.health.app.utils.GetToast;
import com.nf.health.app.utils.LogUtil;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.ViewUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class EcgAnalyzerActivity extends BaseActivity {

    private static final String TAG = "EcgAnalyzerActivity";
    @Bind(R.id.ll_main_ecg)
    LinearLayout ll_main_ecg;
    @Bind(R.id.tv_questory_history_ecg)
    TextView tv_questory_history_ecg;
    /*@Bind(R.id.iv_real)
    ImageView ivReal;*/
   /* @Bind(R.id.tv_date_desc)
    TextView tvDateDesc;*/
    @Bind(R.id.tv_measuring_time)
    TextView tv_measuring_time;
   /* @Bind(R.id.iv_measuring_result)
    ImageView ivMeasuringResult;*/
    @Bind(R.id.btn_ecg_measure)
    Button btnEcgMeasure;
    private int  pageNo = 1 ;
    private String pageSize = String.valueOf(10);
    private ImageUpLoader upLoader;
    private String toOrigonalData = new String();
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_ecg_analyzer);//汗液数据 layout布局
        ButterKnife.bind(this);
        ViewUtil.setText(this, R.id.titlebar_title_tv, "心电数据");
        //检测是否完善注册信息
        boolean registerInfoCompleted = PreferenceHelper.getBoolean(PreferenceHelper.REGISTER_INFO_COMPLETE,false);
        if (!registerInfoCompleted) {
            DialogHelp.getConfirmDialog(EcgAnalyzerActivity.this, "亲,要先完善个人资料哦", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Bundle bundle = new Bundle();
                    bundle.putString("type", "123");//跟注册时一样的type
                    ActivityUtils.showActivity(EcgAnalyzerActivity.this, RegisterNickActivity.class, bundle);
                }
            }).show();
        }
        //发图片后提交文字
        upLoader = new ImageUpLoader(EcgAnalyzerActivity.this, EcgAnalyzerActivity.this);
        initData();
        initListener();
    }

    private void initListener() {
        btnEcgMeasure.setOnClickListener(this);
        tv_questory_history_ecg.setOnClickListener(this);
       // ll_main_ecg.setOnClickListener(this);
    }

    private void initData() {
        provider.getEcgHistory(String.valueOf(pageNo),pageSize,Act.Flag.ECG_PRIVER_DATA);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.btn_ecg_measure:
                startMeasure();
                break;
            case R.id.tv_questory_history_ecg://查看历史记录
                ActivityUtils.showActivity(EcgAnalyzerActivity.this,EcgHistoryActivity.class);
                break;
            case R.id.ll_main_ecg:

                break;
            default:
                break;
        }
    }

    /**
     * 开启心电测量界面,调用三方arr包
     */
    private void startMeasure() {
    UserInfo userInfo = PreferenceHelper.getUser();
    InstitBean institBean = new InstitBean();
        institBean.setUserID("4525455515455555");
        int age = 0;
        if(!TextUtils.isEmpty(userInfo.getBirthday())){
            try {
                int year = Integer.parseInt(userInfo.getBirthday().split("-")[0]);
                age = Calendar.getInstance().get(Calendar.YEAR) - year;
            }catch (Exception e){
                e.printStackTrace();
            }

        }
        //InstitBean  增加了 isShowResult字段 InstitBean.setIsShowResult(0); 1表示是需要显示分析结果 0表示不显示
        institBean.setAge(age);
        //institBean.setIsShowResult(0);
        String rname ="";
        if(!TextUtils.isEmpty( userInfo.getRname())){
            rname =   userInfo.getRname();
        }else if(!TextUtils.isEmpty( userInfo.getNick())){
            rname =  userInfo.getNick();
        }else{
            rname = "";
        }
        institBean.setUserName(rname);
        institBean.setMechanismNumber("1006");
        institBean.setMechanismPassword("61100A59400A96CBE67DC418F47A9AF5F00FEE5C09595348D27B004928373A86");
        Intent intent = new Intent();
        intent.putExtra("InstitBean", institBean);
        Class  activity =  EcgActivity.class;
        intent.setClass(EcgAnalyzerActivity.this, activity);
        startActivityForResult(intent, 100);
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        switch (actionName) {
            case Act.Flag.ECG_PRIVER_DATA:
                List<EcgHistory> list = (List<EcgHistory>) object;
                if (list != null && list.size() > 0) {
                    final EcgHistory ecgHistory = list.get(0);
                    ll_main_ecg.removeAllViews();
                    ImageView imageView = new ImageView(EcgAnalyzerActivity.this);
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                    imageView.setLayoutParams(layoutParams);
                    imageView.setPadding(20, 20, 20, 20);
                    GlideUtil.loadNetImg(EcgAnalyzerActivity.this, imageView, ecgHistory.getPicsurl(), R.drawable.default_square_image);
                    ll_main_ecg.addView(imageView);
                    ll_main_ecg.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Bundle bundle = new Bundle();
                            ArrayList<String> urls = new ArrayList<String>();
                            urls.add(ecgHistory.getPicsurl());
                            bundle.putStringArrayList("imgUrls",urls);
                            bundle.putInt("position", 0);
                            bundle.putInt("type", PictureActivity.TYPE_NET_IMG);
                            ActivityUtils.showActivity(EcgAnalyzerActivity.this, PictureActivity.class, bundle);
                            urls.clear();
                        }
                    });
                }
                break;
            case Act.Flag.ADD_ECG_PRIVER_DATA:
                GetToast.useString(EcgAnalyzerActivity.this,"数据上传成功");
                provider.requestAddScore("17", "");//添加积分
                initData();
                if(!TextUtils.isEmpty(toOrigonalData)){
                    try {
                        File file = new File(toOrigonalData);
                        File lastFile = file.getParentFile();
                        DataCleanManager.deleteFilesByDirectory(lastFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    toOrigonalData = "";
                }

                break;
            case ImageUpLoader.FLAG:
                String picUrl = object.toString();
                GetToast.useString(EcgAnalyzerActivity.this, "上传图片：    "+object.toString());
                try {
                    String ptype = String.valueOf(2);
                    //文件的本地路径
                    String reportEcgFilePath = toOrigonalData.replace("png", "ecg");
                    byte[] ecgResult  = readStream(reportEcgFilePath);
                    String result = Base64Util.getBaseMsgForByte(ecgResult);
                    provider.addEcgHistoryData(result,picUrl,"",ptype);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    @Override
    public void handleActionError(String actionName, String response, VolleyError error) {
        super.handleActionError(actionName, response, error);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 100) {
            //测量结果图片的本地路径
            String reportImagePath = data.getStringExtra("ReportPath");

            EcgAnalyzeResponse response = (EcgAnalyzeResponse) data.getSerializableExtra("result");
            //ivMeasuringResult.setImageBitmap(BitmapFactory.decodeFile(reportImagePath));
            // tvMeasuringResult.setText(response.getDGSResult());
            if (!response.getDGSResult().contains("请重新")) {
                try {
                    upload(reportImagePath);//先上传图片，
                    toOrigonalData = reportImagePath;
                    LogUtil.i(TAG, response.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else{
                GetToast.useString(EcgAnalyzerActivity.this,"解析错误");
            }

        }
    }

    /**
     * 读取文件作为byte[]数组
     *
     * @param filePath
     * @return
     * @throws Exception
     */
    public static byte[] readStream(String filePath) throws Exception {
        FileInputStream fs = new FileInputStream(filePath);
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while (-1 != (len = fs.read(buffer))) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        fs.close();
        return outStream.toByteArray();
    }
    /**
     * 第一次上传和重新上传
     *
     * @param
     */
    private void upload(String url) {
        upLoader.uploadImage(url);
        //upLoader.uploadImage3(url);
    }
}
